/**
 * 2013-6-2 上午8:48:00 Created By niexiaoqiang
 */

package com.xiaoqiang.network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

import com.xiaoqiang.network.event.ServerMsgEvent;
import com.xiaoqiang.network.listener.ServerMsgListener;
import com.xiaoqiang.util.Logger;

/**
 * socket客户端
 */
public class MySocketClient {
	public InetAddress addr = null;
	public Socket socket = null;
	public PrintWriter out = null;
	public BufferedReader sin;
	public boolean isclose = false;
	private static Logger log = new Logger(MySocketClient.class);
	private Collection<ServerMsgListener> listeners;

	public MySocketClient(String iP, int port) throws Exception {
		addr = InetAddress.getByName(iP);
		socket = new Socket(addr, port);
		sin = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
		ServerMessageReviceThread serverMessageReviceThread = new ServerMessageReviceThread(this);
		new Thread(serverMessageReviceThread).start();
	}

	public void addServerMsgListener(ServerMsgListener listener) {
		if (listeners == null) {
			listeners = new HashSet<ServerMsgListener>();
		}
		listeners.add(listener);
		log.debug("add listener:" + listener.getClass());
	}

	public void removeServerMsgListener(ServerMsgListener listener) {
		if (listeners == null) {
			return;
		}
		listeners.remove(listener);
	}

	public void notifyListeners(ServerMsgEvent event) {
		Iterator<ServerMsgListener> iter = listeners.iterator();
		while (iter.hasNext()) {
			ServerMsgListener listener = (ServerMsgListener) iter.next();
			listener.recivedServerMsg(event);
			log.debug("notify the listener:" + listener.getClass());
		}
	}

	public void close() throws Exception {
		log.debug("Close the Cleicntsocket");
		isclose = true;
		out.close();
		socket.close();
		socket = null;
	}

	public void sendMsg(String msgcontent) {
		synchronized (out) {
			log.debug("Send msessage:" + msgcontent);
			this.out.println(msgcontent);
			this.out.flush();
		}
	}
}
